<template>
  <div>
    <van-dropdown-menu>
      <van-dropdown-item v-model="bill" :options="option1" @change="changeBill" />
      <van-dropdown-item v-model="time" :options="option2" @change="changeTime" />
    </van-dropdown-menu>
    <div v-for="(item, index) in memorandumList" :key="index">
      <div class="box">
        <div>
          <div>
            <span>{{ item.outTime.split('年')[1] }}</span>
            <span></span>
          </div>
          <div>
            <span><span class="hui">出:</span> {{ item.totalExpenditure }}</span>
            <span><span class="hui">入:</span>{{ item.totalIncome }}</span>
          </div>
        </div>
        <div v-for="(e, i) in item.children" :key="i">
          <van-swipe-cell>
            <div class="memorandumList">
              <div>
                <img src="@/assets/role01.png" alt="" width="40" />
                <div>
                  <van-tag color="#ffe1e1" text-color="#ad0000">{{ e.industry }}</van-tag>
                </div>
              </div>
              <div>
                <div>{{ e.notes }}</div>
                <div>{{ e.time }}</div>
              </div>
              <div :style="{ color: e.category == '支出' ? 'green' : 'red' }">
                {{ e.category == '支出' ? '-' + e.money : '+' + e.money }}
              </div>
            </div>
            <template #right>
              <van-button square text="删除" type="danger" class="delete-button" @click="goRomove(e.id)"
                style="height: 100%;" />
            </template>
          </van-swipe-cell>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  queryIndexDBByPage, compositeQueryIndexDBByPage, duplicateRemoval
} from "@/utils/util.js"

export default {
  data() {
    return {
      time: '',
      memorandumList: [],
      page: 1,
      db: '',
      idb: '',
      bill: '',
      option2: [
        { text: '全部月份', value: '' },
      ],
      option1: [
        { text: '全部账单', value: '' },
        { text: '收入', value: '收入' },
        { text: '支出', value: '支出' },
      ],
    };
  },
  created() {
    const _this = this
    _this.$store.dispatch('tools/setDb').then(res => {
      _this.db = res
      _this.queryBill(1)
    })
    _this.$store.dispatch('tools/setIdb').then(res => {
      _this.idb = res
    })
    _this.updateDate()
  },
  watch: {
    bill() {
      this.page = 1
    },
    time() {
      this.page = 1
    },
  },
  mounted() {
    window.addEventListener('scroll', this.showScroll)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.showScroll)
  },
  methods: {
    goRomove(id) {
      const _this = this
      _this.idb.delete({
        tableName: "account",
        condition: (item) => item.id == id,
        success: () => {
          _this.$toast('该账单记录删除成功')
          _this.memorandumList.forEach((e, i) => {
            e.children.forEach((el, index) => {
              if (el.id == id) {
                e.children.splice(index, 1)
              }
            })
          });
        }
      })
    },
    showScroll() {
      const _this = this
      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      const windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      const scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      if (scrollTop + windowHeight >= scrollHeight - 20) {
        if (_this.bill && !_this.time) {
          _this.page++
          queryIndexDBByPage({
            page: _this.page,
            pageSize: 10,
            db: _this.db,
            tableName: 'account',
            queryIndex: 'category',
            queryIndexValue: _this.bill
          }).then(res => {
            _this.memorandumList = _this.memorandumList.concat(_this.recombinationArr(res))
            _this.mergeTime(_this.memorandumList)
          })
        } else if (_this.time && !_this.bill) {
          _this.page++
          queryIndexDBByPage({
            page: _this.page,
            pageSize: 10,
            db: _this.db,
            tableName: 'account',
            queryIndex: 'yearMonth',
            queryIndexValue: _this.time
          }).then(res => {
            _this.memorandumList = _this.memorandumList.concat(_this.recombinationArr(res))
            _this.mergeTime(_this.memorandumList)
          })
        } else if (_this.bill && _this.time) {
          _this.page++
          compositeQueryIndexDBByPage({
            page: _this.page,
            pageSize: 10,
            db: _this.db,
            tableName: "account",
            compositeQueryIndex: "cateAndYM",
            IndexValueOneStart: _this.bill,
            IndexValueOneEnd: _this.bill,
            IndexValueTwoStart: _this.time,
            IndexValueTwoEnd: _this.time
          }).then(res => {
            _this.memorandumList = _this.memorandumList.concat(_this.recombinationArr(res))
            _this.mergeTime(_this.memorandumList)
            // duplicateRemoval(_this.memorandumList, 'id')
          })
        } else if (!_this.bill && !_this.time) {
          _this.page++
          _this.queryBill()
        }
      }
    },
    changeBillAndTime() {
      const _this = this
      compositeQueryIndexDBByPage({
        page: 1,
        pageSize: 10,
        db: _this.db,
        tableName: "account",
        compositeQueryIndex: "cateAndYM",
        IndexValueOneStart: _this.bill,
        IndexValueOneEnd: _this.bill,
        IndexValueTwoStart: _this.time,
        IndexValueTwoEnd: _this.time
      }).then(res => {
        _this.memorandumList = _this.recombinationArr(res)
      })
    },
    changeBill(val) {
      const _this = this
      if (_this.bill && _this.time) {
        _this.changeBillAndTime()
        return
      }
      if (!val && !_this.time) {
        _this.queryBill(1)
        return
      } else if (!val && _this.time) {
        queryIndexDBByPage({
          page: 1,
          pageSize: 10,
          db: _this.db,
          tableName: 'account',
          queryIndex: 'yearMonth',
          queryIndexValue: _this.time
        }).then(res => {
          _this.memorandumList = _this.recombinationArr(res)
        })
      }
      queryIndexDBByPage({
        page: 1,
        pageSize: 10,
        db: _this.db,
        tableName: 'account',
        queryIndex: 'category',
        queryIndexValue: val
      }).then(res => {
        _this.memorandumList = _this.recombinationArr(res)
      })
    },
    changeTime(val) {
      const _this = this
      if (_this.bill && _this.time) {
        _this.changeBillAndTime()
        return
      }
      if (!val && !_this.bill) {
        _this.queryBill(1)
        return
      } else if (!val && _this.bill) {
        queryIndexDBByPage({
          page: 1,
          pageSize: 10,
          db: _this.db,
          tableName: 'account',
          queryIndex: 'category',
          queryIndexValue: _this.bill
        }).then(res => {
          _this.memorandumList = _this.recombinationArr(res)
        })
      }
      queryIndexDBByPage({
        page: 1,
        pageSize: 10,
        db: _this.db,
        tableName: 'account',
        queryIndex: 'yearMonth',
        queryIndexValue: val
      }).then(res => {
        _this.memorandumList = _this.recombinationArr(res)
      })
    },
    updateDate() {
      const date = new Date()
      const year = date.getFullYear()
      for (let i = 1; i < 13; i++) {
        const obj = { text: `${year}年${i}月`, value: `${year}年${i}月` }
        this.option2.push(obj)
      }
    },
    queryBill(val) {
      const _this = this
      if (val != undefined) _this.page = 1
      queryIndexDBByPage({
        page: _this.page,
        pageSize: 10,
        db: _this.db,
        tableName: 'account',
        queryIndex: 'name',
        queryIndexValue: 'yt'
      }).then(res => {
        _this.memorandumList = val != undefined ? _this.recombinationArr(res) : _this.memorandumList.concat(_this.recombinationArr(res))
        _this.mergeTime(_this.memorandumList)
      })
    },
    mergeTime(arr) {
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i].outTime == arr[j].outTime) {
            arr[i].children = arr[i].children.concat(arr[j].children)
            arr[i].totalIncome = parseFloat((arr[i].totalIncome + arr[j].totalIncome).toFixed(12))
            arr[i].totalExpenditure = parseFloat((arr[i].totalExpenditure + arr[j].totalExpenditure).toFixed(12))
            arr.splice(j, 1)
            j--
          }
        }
      }
    },
    recombinationArr(arr) {
      let oldArr = JSON.parse(JSON.stringify(arr))
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i].time == arr[j].time) {
            arr.splice(j, 1)
            j--
          }
        }
      }
      let newArr = arr.map(item => item = { outTime: item.time, totalIncome: 0, totalExpenditure: 0, children: [] })
      oldArr.forEach(e => {
        newArr.forEach(el => {
          if (el.outTime == e.time && e.category == '支出') {
            el.totalExpenditure = parseFloat((+el.totalExpenditure + +e.money).toFixed(12))
          } else if (el.outTime == e.time && e.category == '收入') {
            el.totalIncome = parseFloat((+el.totalIncome + +e.money).toFixed(12))
          }

          if (el.outTime == e.time) {
            el.children.push(e)
          }
        })
      })
      return newArr
    },
  },
}
</script>

<style lang="less" scoped>
.hui {
  opacity: 0.5;
}

.box {
  margin: 10px 0 0 15px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 1px 1px 1px #333;
  width: 91vw;

  &>div:first-child {
    &>div:first-child>span {
      font-weight: bold;
    }

    font-size: 14px;
    margin-bottom: 10px;

    & span {
      margin: 0 5px;
    }
  }

  &>div {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.memorandumList {
  width: 91vw;
  display: flex;
  align-items: center;
  justify-content: space-between;
  &>div:nth-child(1) {
    text-align: center;
  }

  &>div:nth-child(2) {
    max-width: 53.33vw;
    font-size: 15px;

    &>div:nth-child(2) {
      color: #ccc;
      font-size: 14px;
      margin-top: 10px;
    }
  }

  &>div:nth-child(3) {
    font-size: 14px;
  }
}
</style>